package com.wuster.Interceptor;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.wuster.result.Result;
import com.wuster.result.ResultCodeEnum;
import com.wuster.utils.JwtUtil;
import com.wuster.utils.ThreadLocalUtil;
import io.swagger.models.HttpMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;


//拦截器,登录的拦截器
@Component
public class LoginInterceptor implements HandlerInterceptor {


    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //处理跨域请求的options请求
        String method=request.getMethod();
        if(HttpMethod.OPTIONS.toString().equals(method)){
            return true;
        }
        //令牌验证
        String token = request.getHeader("Authorization");
        //验证token
        try{
            //从redis获取相同Token
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            String redisToken = operations.get(token);
            if(redisToken==null){
                //token失效
                throw new RuntimeException();
            }

            Map<String,Object> claims= JwtUtil.parseToken(token);

            //把业务数据存储到ThreadLocal中去
            ThreadLocalUtil.set(claims);

            //不抛出异常，证明验证成功
            //放行
            return true;
        }catch (Exception e){
            //http响应状态码为401
            response.setStatus(401);
//            throw new TokenException(ResultCodeEnum.NO_TOKEN);
            //不放行
            ObjectMapper mapper=new ObjectMapper();
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(Result.error(ResultCodeEnum.NO_TOKEN.getCode(), ResultCodeEnum.NO_TOKEN.getMessage())));
            return false;
        }

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清除ThreadLocal中的数据
        //防止内存泄露
        ThreadLocalUtil.remove();
    }
}
